﻿using System.Collections.Generic;
using System.Text;

namespace SCommunicator
{
    /// <summary>
    /// 文本通讯协议
    /// </summary>
    /// <typeparam name="T">数据解析结果类</typeparam>
    public abstract class TextAnalyzeResult<T> : AnalyzeResult<T> where T : new()
    {
        private string _beginOfLine;
        private string _endOfLine;

        protected TextAnalyzeResult()
        {
            this._beginOfLine = "";
            this._endOfLine = "\r\n";
            this.Encoding = Encoding.ASCII;
        }
        /// <summary>
        /// 默认数据解包方法
        /// </summary>
        /// <param name="buffer">要分析的数据</param>
        /// <returns>分析结果</returns>
        public override SearchResult SearchBuffer(List<byte> buffer)
        {
            string str = this.Encoding.GetString(buffer.ToArray());
            int bgnIndex = str.IndexOf(this._beginOfLine, System.StringComparison.Ordinal);
            if (bgnIndex == -1)
            {
                return SearchResult.None;
            }
            int endIndex = str.IndexOf(this._endOfLine, System.StringComparison.Ordinal);
            if (endIndex == -1)
            {
                return SearchResult.Mask;
            }
            base.Raw = new byte[(endIndex - bgnIndex) + this._endOfLine.Length];
            buffer.CopyTo(bgnIndex, base.Raw, 0, base.Raw.Length);//将Buffer中的数据拷贝到Raw中
            buffer.RemoveRange(bgnIndex, base.Raw.Length);//把拷贝好的数据从缓冲区中移除
            return SearchResult.All;
        }

        /// <summary>
        /// 数据包开始标志
        /// </summary>
        public string BeginOfLine
        {
            get
            {
                return this._beginOfLine;
            }
            set
            {
                this._beginOfLine = value;
            }
        }
        /// <summary>
        /// 数据编码方式
        /// </summary>
        public Encoding Encoding { get; set; }

        /// <summary>
        /// 数据包结束标志
        /// </summary>
        public string EndOfLine
        {
            get
            {
                return this._endOfLine;
            }
            set
            {
                this._endOfLine = value;
            }
        }
    }
}
